package com.revert.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.entity.ZichanguihaiEntity;
import com.entity.ZichanjiechuEntity;
import com.entity.view.ZichanguihaiView;
import com.feign.BorrowFeignService;
import com.entity.RecordRequest;
import com.feign.TokenFeignService;
import com.feign.ZiChanFeignService;
import com.revert.service.RedisService;
import com.revert.service.ZichanguihaiService;
import com.utils.MPUtil;
import com.utils.PageUtils;
import com.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;


/**
 * 资产归还
 * 后端接口
 *
 * @author
 * @email
 * @date 2021-05-11 09:16:46
 */
@RestController
@RequestMapping("/zichanguihai")
public class ZichanguihaiController {
    @Autowired
    private ZichanguihaiService zichanguihaiService;
    @Autowired
    private TokenFeignService tokenFeignService;
    @Autowired
    private BorrowFeignService borrowFeignService;

    @Autowired
    private ZiChanFeignService zixChanFeignService;
    @Resource
    private RedisService redisService;

    /**
     * 后端列表
     */
    @RequestMapping("/page")
    public R page(@RequestParam Map<String, Object> params, ZichanguihaiEntity zichanguihai,
                  HttpServletRequest request) {
        String tableName = tokenFeignService.getCurrentUserByToken(request.getHeader("Token")).getTablename();
        if (tableName.equals("yonghu")) {
            zichanguihai.setYonghuming(tokenFeignService.getCurrentUserByToken(request.getHeader("Token")).getUsername());
        }
        EntityWrapper<ZichanguihaiEntity> ew = new EntityWrapper<ZichanguihaiEntity>();
        PageUtils page = zichanguihaiService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, zichanguihai), params), params));

        return R.ok().put("data", page);
    }

    /**
     * 前端列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params, ZichanguihaiEntity zichanguihai,
                  HttpServletRequest request) {
        EntityWrapper<ZichanguihaiEntity> ew = new EntityWrapper<ZichanguihaiEntity>();
        PageUtils page = zichanguihaiService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, zichanguihai), params), params));
        return R.ok().put("data", page);
    }

    /**
     * 列表
     */
    @RequestMapping("/lists")
    public R list(ZichanguihaiEntity zichanguihai) {
        EntityWrapper<ZichanguihaiEntity> ew = new EntityWrapper<ZichanguihaiEntity>();
        ew.allEq(MPUtil.allEQMapPre(zichanguihai, "zichanguihai"));
        return R.ok().put("data", zichanguihaiService.selectListView(ew));
    }

    /**
     * 查询
     */
    @RequestMapping("/query")
    public R query(ZichanguihaiEntity zichanguihai) {
        EntityWrapper<ZichanguihaiEntity> ew = new EntityWrapper<ZichanguihaiEntity>();
        ew.allEq(MPUtil.allEQMapPre(zichanguihai, "zichanguihai"));
        ZichanguihaiView zichanguihaiView = zichanguihaiService.selectView(ew);
        return R.ok("查询资产归还成功").put("data", zichanguihaiView);
    }

    /**
     * 后端详情
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id) {
        ZichanguihaiEntity zichanguihai = (ZichanguihaiEntity) redisService.get("Zichanguihai" + id);
        if (zichanguihai == null) {
            zichanguihai = zichanguihaiService.selectById(id);
            redisService.set("Zichanguihai" + id,zichanguihai);
        }


        return R.ok().put("data", zichanguihai);
    }

    /**
     * 前端详情
     */
    @RequestMapping("/detail/{id}")
    public R detail(@PathVariable("id") Long id) {
        ZichanguihaiEntity zichanguihai = (ZichanguihaiEntity) redisService.get("Zichanguihai" + id);
        if (zichanguihai == null) {
            zichanguihai = zichanguihaiService.selectById(id);
            redisService.set("Zichanguihai" + id,zichanguihai);
        }
        return R.ok().put("data", zichanguihai);
    }


    /**
     * 后端保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody ZichanguihaiEntity zichanguihai, HttpServletRequest request) {
        //查询资产信息，看看是否有借出情况
        zichanguihai.setId(new Date().getTime() + new Double(Math.floor(Math.random() * 1000)).longValue());
        //ValidatorUtils.validateEntity(zichanguihai);
        RecordRequest recordRequest = new RecordRequest();
        recordRequest.setZichanbianhao(zichanguihai.getZichanbianhao());
        recordRequest.setYonghuming(zichanguihai.getYonghuming());
        ZichanjiechuEntity record = borrowFeignService.record(recordRequest);
        if (record == null) {
            return R.error("没有借出当前资产");
        }
        if (record.getShuliang() < zichanguihai.getShuliang()) {
            return R.error("归还数量大于借出量，请检查数据");
        }
        zichanguihaiService.insert(zichanguihai);
        redisService.set("Zichanguihai" + zichanguihai.getId(),zichanguihai);

        return R.ok();
    }

    /**
     * 前端保存
     */
    @RequestMapping("/add")
    public R add(@RequestBody ZichanguihaiEntity zichanguihai, HttpServletRequest request) {
        zichanguihai.setId(new Date().getTime() + new Double(Math.floor(Math.random() * 1000)).longValue());
        //ValidatorUtils.validateEntity(zichanguihai);
        RecordRequest recordRequest = new RecordRequest();
        recordRequest.setZichanbianhao(zichanguihai.getZichanbianhao());
        recordRequest.setYonghuming(zichanguihai.getYonghuming());
        ZichanjiechuEntity record = borrowFeignService.record(recordRequest);
        if (record == null) {
            return R.error("没有借出当前资产");
        }

        if (record.getShuliang() < zichanguihai.getShuliang()) {
            return R.error("归还数量大于借出量，请检查数据");
        }
        zichanguihaiService.insert(zichanguihai);
        redisService.set("Zichanguihai" + zichanguihai.getId(),zichanguihai);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody ZichanguihaiEntity zichanguihai, HttpServletRequest request) {
        final ZichanguihaiEntity zichanguihaiEntity = zichanguihaiService.selectById(zichanguihai.getId());
        //ValidatorUtils.validateEntity(zichanguihai);
        final String sfsh = zichanguihai.getSfsh();
        if (zichanguihaiEntity.getSfsh().equals("是")) {
            return R.error("已审核通过");
        }
        if (sfsh.equals("是")) {
            zixChanFeignService.record(zichanguihai.getZichanbianhao(), zichanguihai.getShuliang());
        }
        zichanguihaiService.updateById(zichanguihai);//全部更新
        redisService.set("Zichanguihai" + zichanguihai.getId(),zichanguihai);

        return R.ok();
    }


    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids) {
        zichanguihaiService.deleteBatchIds(Arrays.asList(ids));
        for (Long id : ids) {
            redisService.delete("Zichanguihai" +id);
        }
        return R.ok();
    }

    /**
     * 提醒接口
     */
    @RequestMapping("/remind/{columnName}/{type}")
    public R remindCount(@PathVariable("columnName") String columnName, HttpServletRequest request,
                         @PathVariable("type") String type, @RequestParam Map<String, Object> map) {
        map.put("column", columnName);
        map.put("type", type);

        if (type.equals("2")) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar c = Calendar.getInstance();
            Date remindStartDate = null;
            Date remindEndDate = null;
            if (map.get("remindstart") != null) {
                Integer remindStart = Integer.parseInt(map.get("remindstart").toString());
                c.setTime(new Date());
                c.add(Calendar.DAY_OF_MONTH, remindStart);
                remindStartDate = c.getTime();
                map.put("remindstart", sdf.format(remindStartDate));
            }
            if (map.get("remindend") != null) {
                Integer remindEnd = Integer.parseInt(map.get("remindend").toString());
                c.setTime(new Date());
                c.add(Calendar.DAY_OF_MONTH, remindEnd);
                remindEndDate = c.getTime();
                map.put("remindend", sdf.format(remindEndDate));
            }
        }

        Wrapper<ZichanguihaiEntity> wrapper = new EntityWrapper<ZichanguihaiEntity>();
        if (map.get("remindstart") != null) {
            wrapper.ge(columnName, map.get("remindstart"));
        }
        if (map.get("remindend") != null) {
            wrapper.le(columnName, map.get("remindend"));
        }

        String tableName = tokenFeignService.getCurrentUserByToken(request.getHeader("Token")).getTablename();
        if (tableName.equals("yonghu")) {
            wrapper.eq("yonghuming", tokenFeignService.getCurrentUserByToken(request.getHeader("Token")).getUsername());
        }
        int count = zichanguihaiService.selectCount(wrapper);
        return R.ok().put("count", count);
    }


}
